<template>
  <div class="tag-manage">
    <div class="page-header">
      <h2>标签管理</h2>
      <el-button type="primary" @click="handleCreateTag">
        <el-icon><Plus /></el-icon>
        新增标签
      </el-button>
    </div>
    
    <div class="layout-container">
      <!-- 热门标签云 -->
      <el-card class="section-card">
        <template #header>
          <span>热门标签</span>
        </template>
        
        <div class="tag-cloud">
          <el-tag
            v-for="tag in hotTags"
            :key="tag.id"
            :type="tag.type"
            closable
            @close="handleRemoveTag(tag)"
            class="tag-item"
          >
            {{ tag.name }} 
          </el-tag>
        </div>
        
        <el-divider />
        
        <!-- 标签列表 -->
        <div class="table-header">
          <span>标签列表</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索标签名称"
              style="width: 200px; margin-right: 10px;"
              clearable
              @input="handleSearch"
            />
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
        
        <el-table :data="filteredTagList" v-loading="tagLoading">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="name" label="标签名称" />
          <el-table-column prop="type" label="标签类型" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.type || 'info'">
                {{ getTagTypeText(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="usageCount" label="使用次数" width="100" />
          <el-table-column prop="createdAt" label="创建时间" width="180" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click="handleEditTag(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDeleteTag(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    
    <!-- 标签编辑对话框 -->
    <el-dialog
      v-model="tagDialogVisible"
      :title="tagDialogTitle"
      width="500px"
    >
      <el-form :model="tagForm" label-width="80px">
        <el-form-item label="标签名称">
          <el-input v-model="tagForm.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="标签类型">
          <el-select v-model="tagForm.type" placeholder="请选择标签类型">
            <el-option label="普通" value="" />
            <el-option label="热门" value="success" />
            <el-option label="推荐" value="warning" />
            <el-option label="新品" value="danger" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="tagDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleTagSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { tagService } from '../../services/tagService'

const tagLoading = ref(false)
const tagDialogVisible = ref(false)
const tagDialogTitle = ref('新增标签')
const searchKeyword = ref('')

const hotTags = ref([])
const tagList = ref([])

const tagForm = reactive({
  id: null,
  name: '',
  type: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 过滤后的标签列表
const filteredTagList = computed(() => {
  let filtered = tagList.value
  
  if (searchKeyword.value) {
    filtered = filtered.filter(tag => 
      tag.name?.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  
  // 前端分页
  const startIndex = (pagination.current - 1) * pagination.size
  const endIndex = startIndex + pagination.size
  pagination.total = filtered.length
  
  return filtered.slice(startIndex, endIndex)
})

// 获取标签类型文本
const getTagTypeText = (type) => {
  const typeMap = {
    '': '普通',
    'success': '热门',
    'warning': '推荐',
    'danger': '新品'
  }
  return typeMap[type] || '普通'
}

// 加载标签列表
const loadTags = async () => {
  tagLoading.value = true
  try {
    const [tagsResponse, hotTagsResponse] = await Promise.all([
      tagService.getAllTags(),
      tagService.getHotTags()
    ])
    tagList.value = tagsResponse.data || []
    hotTags.value = hotTagsResponse.data || []
  } catch (error) {
    console.error('加载标签列表失败:', error)
    ElMessage.error('加载标签列表失败')
  } finally {
    tagLoading.value = false
  }
}

const handleCreateTag = () => {
  tagDialogTitle.value = '新增标签'
  Object.assign(tagForm, {
    id: null,
    name: '',
    type: ''
  })
  tagDialogVisible.value = true
}

const handleEditTag = (row) => {
  tagDialogTitle.value = '编辑标签'
  Object.assign(tagForm, { ...row })
  tagDialogVisible.value = true
}

const handleDeleteTag = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除标签 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await tagService.deleteTag(row.id)
    ElMessage.success('删除成功')
    loadTags()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除标签失败:', error)
      ElMessage.error('删除标签失败')
    }
  }
}

const handleRemoveTag = async (tag) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除热门标签 "${tag.name}" 吗？`,
      '移除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await tagService.deleteTag(tag.id)
    ElMessage.success('移除成功')
    loadTags()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除标签失败:', error)
      ElMessage.error('移除标签失败')
    }
  }
}

const handleTagSubmit = async () => {
  try {
    if (tagForm.id) {
      // 编辑标签
      await tagService.updateTag(tagForm.id, tagForm)
      ElMessage.success('编辑标签成功')
    } else {
      // 新增标签
      await tagService.createTag(tagForm)
      ElMessage.success('新增标签成功')
    }
    
    tagDialogVisible.value = false
    loadTags()
  } catch (error) {
    console.error('保存标签失败:', error)
    ElMessage.error('保存标签失败')
  }
}

const handleSearch = () => {
  pagination.current = 1
}

const handleReset = () => {
  searchKeyword.value = ''
  pagination.current = 1
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
}

const handleCurrentChange = (current) => {
  pagination.current = current
}

onMounted(() => {
  loadTags()
})
</script>

<style scoped>
.tag-manage {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 0 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.layout-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 0 20px;
}

.section-card {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
}

.section-card :deep(.el-card__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 16px 20px;
  font-weight: 600;
  color: #2c3e50;
}

.section-card :deep(.el-card__body) {
  padding: 20px;
}

.section-card :deep(.el-table) {
  text-align: center;
}

.section-card :deep(.el-table th) {
  background-color: #f8f9fa;
  text-align: center;
  font-weight: 600;
  color: #2c3e50;
}

.section-card :deep(.el-table td) {
  text-align: center;
}

.tag-cloud {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 20px;
  justify-content: center;
  padding: 10px;
}

.tag-item {
  margin: 4px;
  cursor: pointer;
  border-radius: 16px;
  padding: 6px 12px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.tag-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
</style>